import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import Login from '../views/Login.vue';
import PublicActivities from '../views/PublicActivities.vue';
import ActivityDetail from '../views/ActivityDetail.vue';
import ActivityManagement from '../views/ActivityManagement.vue';

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: '/public-activities',
    children: [
      {
        path: '/public-activities',
        name: 'PublicActivities',
        component: PublicActivities,
        meta: { requiresAuth: true }
      },
      {
        path: '/public-activities/:id',
        name: 'ActivityDetail',
        component: ActivityDetail,
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/activity-management',
    name: 'ActivityManagement',
    component: ActivityManagement,
    meta: { requiresAuth: true, requiresAdmin: true }
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('isLoggedIn') === 'true';
  const userRole = localStorage.getItem('userRole');

  // 需要认证的页面
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login');
  } 
  // 管理员专属页面
  else if (to.meta.requiresAdmin && userRole !== 'admin') {
    alert('无权限访问该页面');
    next('/');
  } 
  else {
    next();
  }
});

export default router;